using B.S.XZYData.Api.Wrter.Application.Command.WorkReportDefectiveItem;
using DomainWorkReportDefectiveItem = B.S.XZYData.Domain.ZSH.WorkReportDefectiveItem;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkReportDefectiveItem
{
    /// <summary>
    /// 导出报工-不良品项子表（无样式 Excel）
    /// </summary>
    public class ExportWorkReportDefectiveItemsHandler : IRequestHandler<ExportWorkReportDefectiveItemsQuery, byte[]>
    {
        private readonly IBaseRepository<DomainWorkReportDefectiveItem> _repo;
        private readonly IBaseRepository<AccountModel> _accountRepo;

        public ExportWorkReportDefectiveItemsHandler(IBaseRepository<DomainWorkReportDefectiveItem> repo, IBaseRepository<AccountModel> accountRepo)
        {
            _repo = repo;
            _accountRepo = accountRepo;
        }

        public async Task<byte[]> Handle(ExportWorkReportDefectiveItemsQuery request, CancellationToken cancellationToken)
        {
            // 查询该报工Id下的子表数据，排除已删除
            var list = _repo.GetAll().Where(x => !x.IsDeleted && x.WorkReportId == request.WorkReportId).OrderBy(x => x.Id).ToList();

            // 收集用户信息
            var creatorIds = list.Select(x => (long)x.CreatorId).Distinct().ToList();
            var modifierIds = list.Where(x => x.ModifierId.HasValue).Select(x => (long)x.ModifierId.Value).Distinct().ToList();
            var allIds = creatorIds.Concat(modifierIds).Distinct().ToList();
            var users = _accountRepo.GetAll().Where(u => allIds.Contains(u.Id)).ToList();

            IWorkbook wb = new XSSFWorkbook();
            var sheet = wb.CreateSheet("报工-不良品项");

            // 表头
            var header = sheet.CreateRow(0);
            header.CreateCell(0).SetCellValue("序号");
            header.CreateCell(1).SetCellValue("报工ID");
            header.CreateCell(2).SetCellValue("不良品项编码");
            header.CreateCell(3).SetCellValue("不良数量");
            header.CreateCell(4).SetCellValue("创建时间");
            header.CreateCell(5).SetCellValue("创建人");
            header.CreateCell(6).SetCellValue("修改时间");
            header.CreateCell(7).SetCellValue("修改人");

            // 数据行
            for (int i = 0; i < list.Count; i++)
            {
                var item = list[i];
                var row = sheet.CreateRow(i + 1);

                var creatorName = users.FirstOrDefault(u => u.Id == (long)item.CreatorId)?.RealName ?? string.Empty;
                var modifierName = item.ModifierId.HasValue ? users.FirstOrDefault(u => u.Id == (long)item.ModifierId.Value)?.RealName ?? string.Empty : string.Empty;

                row.CreateCell(0).SetCellValue(item.Id);
                row.CreateCell(1).SetCellValue(item.WorkReportId);
                row.CreateCell(2).SetCellValue(item.DefectiveCode ?? string.Empty);
                row.CreateCell(3).SetCellValue(item.DefectiveQty);
                row.CreateCell(4).SetCellValue(item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                row.CreateCell(5).SetCellValue(creatorName);
                row.CreateCell(6).SetCellValue(item.ModifyTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty);
                row.CreateCell(7).SetCellValue(modifierName);
            }

            using var ms = new MemoryStream();
            wb.Write(ms);
            return ms.ToArray();
        }
    }
} 